<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      points: [],
      markers: [],
      cluster: null,
      geocoder: null,
      districtSearch: null,
      districtData: {},
      clusterIndexSet: {
        city: { minZoom: 2, maxZoom: 10 },
        district: { minZoom: 10, maxZoom: 12 },
        area: { minZoom: 12, maxZoom: 15 },
        community: { minZoom: 15, maxZoom: 22 },
      },
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
  async fetchEquipmentList() {
    try {
      const res = await getequipmentlist({ limit: 10000000 });
      this.points = res.msg
        .filter(item => item.lat && item.lng)
        .map(item => ({
          lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
        }));

      this.initMarkers();
      if (this.map) {
        this.initCluster();
      }

      await this.getAddressesFromPoints(this.points);
    } catch (error) {
      console.error('Error fetching equipment list:', error);
    }
  },
  async getAddressesFromPoints(points) {
    for (const point of points) {
      try {
        const address = await this.getAddressFromCoordinates(point.lnglat[0], point.lnglat[1]);
        const region = this.getRegionFromAddress(address);
        if (!this.districtData[region]) {
          this.districtData[region] = [];
        }
        this.districtData[region].push(point);
      } catch (error) {
        console.error(`Error fetching address for coordinates (${point.lnglat[0]}, ${point.lnglat[1]}): ${error}`);
      }
    }
    this.initCluster();
  },
  getAddressFromCoordinates(lng, lat) {
    return new Promise((resolve, reject) => {
      if (!this.geocoder) {
        reject(new Error('Geocoder is not initialized'));
        return;
      }

      this.geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const address = result.regeocode.formattedAddress || 'Unknown address';
          resolve(address);
        } else {
          reject(new Error('Geocoding failed'));
        }
      });
    });
  },
  async initAMap() {
    await this.loadAMapScript();
    AMapLoader.load({
      key: "YOUR_AMAP_KEY", // Replace with your API Key
      version: "2.0",
      plugins: ["AMap.Scale", "AMap.MarkerClusterer", "AMap.Geocoder", "AMap.DistrictSearch"], // Required plugins
    })
      .then((AMap) => {
        this.map = new AMap.Map("container", {
          viewMode: "3D",
          zoom: 4,
          center: [116.397428, 39.90923],
          mapStyle: "amap://styles/blue",
        });

        this.map.addControl(new AMap.Scale());

        this.geocoder = new AMap.Geocoder();
        this.districtSearch = new AMap.DistrictSearch({ subdistrict: 1, extensions: 'base' });

        this.initMarkers();
        this.initCluster();
      })
      .catch((e) => {
        console.error('Error initializing AMap:', e);
      });
  },
},

};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100vh;
}
.amap-cluster {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}
.showName {
  font-size: 14px;
}
.showCount,
.showName {
  display: block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
